﻿namespace Tiny.Imaging.Filter.PixelLibrary
{
    public struct Hsl
    {
        public float H;
        public float L;
        public float S;

        public Rgba ToRgba()
        {
            float r, g, b;

            if (S == 0)
            {
                r = g = b = L;
            }
            else
            {
                float q = L < 0.5f ? L*(1 + S) : L + S - L*S;
                float p = 2*L - q;

                r = Hue2Rgb(p, q, H + 1.0f/3.0f);
                g = Hue2Rgb(p, q, H);
                b = Hue2Rgb(p, q, H - 1.0f/3.0f);
            }

            return new Rgba
                       {
                           R = MathLibrary.MathLibrary.Clamp(r*255),
                           G = MathLibrary.MathLibrary.Clamp(g*255),
                           B = MathLibrary.MathLibrary.Clamp(b*255),
                           A = 255
                       };
        }

        private float Hue2Rgb(float p, float q, float t)
        {
            if (t < 0) t += 1;
            if (t > 1) t -= 1;
            if (t < 1.0f/6.0f) return p + (q - p)*6*t;
            if (t < 0.5f) return q;
            if (t < 2.0f/3.0f) return p + (q - p)*(2.0f/3.0f - t)*6;
            return p;
        }
    }
}